package com.wbtech.cobub;

import com.wbtech.cobub.model.Locations;
import com.wbtech.cobub.service.LocationService;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class GPSActivity extends Activity{

	public static final String GPS = "gps";
	public static final String NETWORK = "network";
	protected LocationManager mLocationManager;
	protected static final String PROVIDER_NAME = LocationManager.GPS_PROVIDER;
	protected SampleLocationListener mLocationListener, mNetListener;
	public int mNumSatellites = 0;
	private boolean mGPSFastUpdate = true;
	
	private String latitudeString = "";
	private String longitudeString = "";
	
	
	 @Override
	    public void onCreate(Bundle savedInstanceState) {
	        super.onCreate(savedInstanceState);
	        setContentView(R.layout.gps);
	        initLocation();
	   	 	Button btnSearch = (Button)findViewById(R.id.btnSearch);
	        btnSearch.setOnClickListener(new OnClickListener() {
				
				
				public void onClick(View v) {
					
					if(latitudeString.equals(""))
		    		{
		    			Toast.makeText(getApplicationContext(), "GPS信息不能为空", Toast.LENGTH_SHORT).show();
		    			return;
		    		}
					
					WSAsyncTask task = new WSAsyncTask();
		    		task.execute();				
				}
			});
	        
	        Button btnMap = (Button)findViewById(R.id.btnViewMap);
		      btnMap.setOnClickListener(new OnClickListener() {					
					public void onClick(View v) {
						if(latitudeString.equals("")||longitudeString.equals(""))
						{
							Toast.makeText(getApplicationContext(), "当前无GPS数据", Toast.LENGTH_SHORT).show();
							return;
						}
						Intent mapIntent = new Intent(GPSActivity.this,MapsActivity.class);
						mapIntent.putExtra("latitude", latitudeString);
						mapIntent.putExtra("longitude", longitudeString);
						startActivity(mapIntent);
					}
				});
	    }
	 
	 private LocationManager getLocationManager() {
			if (this.mLocationManager == null)
				this.mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
			return this.mLocationManager;
		}
	 
	 private void getBestProvider() {
			int minTime = 0;
			int minDistance = 0;

			if (!mGPSFastUpdate) {
				minTime = 2000;
				minDistance = 20;
			}
			;

			getLocationManager().removeUpdates(mLocationListener);
			if (mNetListener != null)
				getLocationManager().removeUpdates(mNetListener);

			if (getLocationManager().isProviderEnabled(GPS)) {
				getLocationManager().requestLocationUpdates(GPS, minTime,
						minDistance, this.mLocationListener);

				try {
					if (getLocationManager().isProviderEnabled(NETWORK)) {
						this.mNetListener = new SampleLocationListener();
						getLocationManager().requestLocationUpdates(NETWORK,
								minTime, minDistance, this.mNetListener);
					}
				} catch (Exception e) {
					Log.e("NETWROK", "isProviderEnabled(NETWORK) exception");
					e.printStackTrace();
				}

			} else if (getLocationManager().isProviderEnabled(NETWORK)) {
				getLocationManager().requestLocationUpdates(NETWORK, minTime,
						minDistance, this.mLocationListener);
			}
		}

		private void initLocation() {
			this.mLocationListener = new SampleLocationListener();
		}

		public void onLocationLost() {
		}

		public void onLocationChanged(Location loc) {
			
		 latitudeString = String.valueOf(loc.getLatitude());
		 longitudeString = String.valueOf(loc.getLongitude());
		
		 TextView cellText = (TextView)findViewById(R.id.textCellInfo);
		 cellText.setText("经度:"+longitudeString + "\n纬度:"+latitudeString);
		}

		public void onStatusChanged(String provider, int status, Bundle extras) {
			// int cnt = extras.getInt("satellites", Integer.MIN_VALUE);
			// mStatusListener = provider+ " " + status + " " + (cnt >= 0 ? cnt :
			// 0);
			// setTitle();
		}

		/**
		 * Called when activity is destroyed. Unregisters LocationListener.
		 */
		@Override
		protected void onDestroy() {
			super.onDestroy();
			getLocationManager().removeUpdates(mLocationListener);
			if (mNetListener != null)
				getLocationManager().removeUpdates(mNetListener);

			// if(this.mDoGPSRecordingAndContributing){
			// OSMUploader.uploadAsync(this.mRouteRecorder.getRecordedGeoPoints());
			// }
		}

		@Override
		protected void onStart() {
			getBestProvider();
			super.onStart();
		}

		@Override
		protected void onStop() {
			getLocationManager().removeUpdates(mLocationListener);
			super.onStop();
		}

		protected void StatusChanged(String provider, int status, Bundle b) {
			// Log.e(DEBUGTAG, "onStatusChanged povider = " + provider +
			// " status = " + status + " satellites = " + b.getInt("satellites",
			// NOT_SET));
			if (mNetListener != null) {
				if (provider.equals(GPS) && status == 2) {
					getLocationManager().removeUpdates(mNetListener);
					mNetListener = null;
					Log.e("NETWORK", "Stop NETWORK listener");
				}
			}
			if (mNetListener == null)
				GPSActivity.this.onStatusChanged(provider, status, b);
			else if (mNetListener != null && provider.equals(NETWORK))
				GPSActivity.this.onStatusChanged(provider, status, b);

		}
		
		 class WSAsyncTask extends AsyncTask
		    {
		    	ProgressDialog dialog = null;

		    	protected Object doInBackground(Object... params)
		    	{
					Locations loation = LocationService.GetAddressByCord(latitudeString, longitudeString, "zh-CN");
					return loation;
		    	}

				@Override
				protected void onPreExecute() {
					super.onPreExecute();
					dialog = new ProgressDialog(GPSActivity.this);
					dialog.setCancelable(false);
					dialog.setTitle("地址查询...");
					dialog.setMessage("查询中,请稍候...");
					dialog.show();
				}

				@Override
				protected void onPostExecute(Object result) {
					super.onPostExecute(result);
			        setProgressBarIndeterminateVisibility(false);
					dialog.dismiss();
					Locations ret = (Locations)result;
					if(ret.getFlag() == null || ret.getMsg() == null)
					{
						Dialog messageDialog = buildMessageDialog(GPSActivity.this,"查询失败,当前网络较慢或无连接，请稍后重试....");
						messageDialog.show();
					}
					else if(ret.getFlag())
					{
						   ((TextView)findViewById(R.id.textLatitudeValue)).setText(ret.getLatitude());
						   ((TextView)findViewById(R.id.textLongitudeValue)).setText(ret.getLongitude());
						       
					       ((TextView)findViewById(R.id.textCountryValue)).setText(ret.getCountry());
					       ((TextView)findViewById(R.id.textRegionValue)).setText(ret.getRegion());
					       ((TextView)findViewById(R.id.textCountryValue)).setText(ret.getCounty());
					       ((TextView)findViewById(R.id.textCitryValue)).setText(ret.getCity());
					       ((TextView)findViewById(R.id.textStreetValue)).setText(ret.getStreet());
					       ((TextView)findViewById(R.id.textStreetNumberValue)).setText(ret.getStreetNumber());
					       ((TextView)findViewById(R.id.textPostalCodeValue)).setText(ret.getPostalcode());
					       ((TextView)findViewById(R.id.textCountryValue)).setText(ret.getCountry());
					}
					else
					{
						Dialog messageDialog = buildMessageDialog(GPSActivity.this,ret.getMsg());
						messageDialog.show();
					}
				}
		    }
		  
		  
		 private Dialog buildMessageDialog(Context context,String message) {
				AlertDialog.Builder builder = new AlertDialog.Builder(context);
				builder.setIcon(R.drawable.icon);
				builder.setTitle("Cobub提示");
				builder.setMessage(message);
				builder.setPositiveButton("确定",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int whichButton) {
								setTitle("Cobub提示");
							}
						});
				return builder.create();

			}
	 
	 private class SampleLocationListener implements LocationListener {
			public void onLocationChanged(final Location loc) {
				if (loc != null) {
					// if(OpenStreetMapActivity.this.mDoGPSRecordingAndContributing)
					// OpenStreetMapActivity.this.mRouteRecorder.add(loc,
					// OpenStreetMapActivity.this.mNumSatellites);

					GPSActivity.this.onLocationChanged(loc);
				} else {
					GPSActivity.this.onLocationLost();
				}
			}

			public void onStatusChanged(String a, int status, Bundle b) {
				GPSActivity.this.mNumSatellites = b.getInt("satellites",
						0); // LATER Check on an actual device
				// Log.e(DEBUGTAG, "onStatusChanged status = " + status +
				// " satellites = " + b.getInt("satellites", NOT_SET));
				StatusChanged(a, status, b);
			}

			public void onProviderEnabled(String a) {
				Log.e("NETWORK", "onProviderEnabled");
				getBestProvider();
			}

			public void onProviderDisabled(String a) {
				Log.e("NETWORK", "onProviderDisabled");
				getBestProvider();
			}
		}
	 
	  private Dialog ExitDialog(Context context) {
			AlertDialog.Builder builder = new AlertDialog.Builder(context);
			builder.setIcon(R.drawable.icon);
			builder.setTitle("Cobub提示");
			builder.setMessage("确定退出么?");
			builder.setPositiveButton("确定",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int whichButton) {
							finish();
						}
					});
			builder.setNegativeButton("取消",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int whichButton) {

						}
					});
			return builder.create();
		}
	   
	    @Override
		public boolean onKeyDown(int keyCode, KeyEvent event) {
			if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
				ExitDialog(GPSActivity.this).show();
				return true;
			}
			return super.onKeyDown(keyCode, event);
		}
}
